package r25.room;

import java.util.List;

import r25.character.ICharacter;
import r25.engine.IEvent;
import r25.engine.IEvent.EVENT;
import r25.engine.IGameInstance;
import r25.engine.IGameInstance.GAME_WINNER;
import r25.engine.IGameService.CHARACTER_ROLE;

/**
 * Exit room. When all the prisoners have entered this room, one of them has to
 * move it out of the Complex using the Control action.
 * 
 * @author u211354
 * 
 */
public class Room25 extends AbstractRoom {
	@Override
	public void check(IGameInstance gi, boolean endOfTurn, IEvent s) {
		// overriding super.check() that invalidates ROOM_OUT_OF_COMPLEX

		// process only own event ROOM_OUT_OF_COMPLEX
		if (!EVENT.ROOM_OUT_OF_COMPLEX.equals(s.getType())) {
			return;
		}

		// count prisoners
		if (s.isValid()) {
			List<ICharacter> chs = gi.getOtherCharactersInRoomObjects(this,
					null);
			int countOutPrisoners = 0;
			for (ICharacter c : chs) {
				if (c.isAlive()
						&& (CHARACTER_ROLE.PRISONER.equals(c.getRole()))) {
					countOutPrisoners++;
				}
			}

			// TODO remove debug "too easy" rule
			if (countOutPrisoners > 0) {
				gi.gameOver(GAME_WINNER.PRISONERS);
				return;
			}

			int lastTurnDistance = gi.getMaxTurn() - gi.getTurnIndex();
			if (lastTurnDistance == 0) {
				// accept 1 missing prisoners in the last turn
				if ((gi.getPrisonersCount() - countOutPrisoners) <= 1) {
					gi.gameOver(GAME_WINNER.PRISONERS);
				}
			} else {
				// require all prisoners before the last turn
				if (gi.getPrisonersCount() == countOutPrisoners) {
					gi.gameOver(GAME_WINNER.PRISONERS);
				}
			}
		}

		// test only once
		s.setValid(false);
	}
}
